package demo16;
import java.io.*;
// 定义一个可序列化的类
class Person implements java.io.Serializable {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class DeserializeDemo {
    public static void main(String[] args) {
        Person person = new Person("John", 30);
        try {
            FileOutputStream fileOut = new FileOutputStream("./src/main/java/demo16/person.txt");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(person);
            out.close();
            fileOut.close();
            System.out.println("对象已序列化到person.txt");
        } catch(IOException e) {
            e.printStackTrace();
        }

        try {
            // 创建一个文件输入流
            FileInputStream fileIn = new FileInputStream("./src/main/java/demo16/person.txt");
            // 创建一个对象输入流
            ObjectInputStream in = new ObjectInputStream(fileIn);
            // 从对象输入流中读取对象
            person = (Person) in.readObject();
            // 关闭对象输入流
            in.close();
            // 关闭文件输入流
            fileIn.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        if (person != null) {
            System.out.println("Name: " + person.getName());
            System.out.println("Age: " + person.getAge());
        }
    }
}
